import 'package:cher_flare/routes/app_pages.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../../config/config.dart';
import '../../../config/url_api.dart';
import '../../../http/http_utils.dart';
import '../../../utils/ly_use_log_manager.dart';
import '../models/ly_login_info_manager.dart';

class LYLoginController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    _requestConfig();
  }

  void login(bool isFastLogin, {String? token}) async {
    if (isFastLogin) {
      LYUseLogManager.stat(page: LYLogPages.quickLogin);
    }
    EasyLoading.show();
    final opt = Options(contentType: "application/x-www-form-urlencoded");
    Map<String, dynamic> parameters = {
      'oauthType': isFastLogin ? 4 : 3,
      'token': isFastLogin ? Config.deviceId : token,
      'ver': Config.version
    };
    final res = await HttpUtils.getInstance
        .post(URLApi.login, data: parameters, options: opt);
    await LYLoginInfoManager.getInstance.saveLoginInfo(res.data);
    EasyLoading.dismiss();
    LYUseLogManager.stat(page: LYLogPages.loginSuccess);
    Get.offAllNamed(AppPages.home, arguments: {'show': true});
  }

  void appleLogin() async {
    LYUseLogManager.stat(page: LYLogPages.appleLogin);
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    debugPrint('=========${credential.identityToken}');
    login(false, token: credential.identityToken);
  }

  void _requestConfig() async {
    EasyLoading.show();
    final res = await HttpUtils.getInstance
        .get(URLApi.appConfig, queryParameters: {'ver': 0});
    final data = res.data;
    if (data is Map) {
      final items = data['items'];
      if (items is List) {
        for (final item in items) {
          if (item['name'] == 'rck') {
            Config.rck = item['data'];
          } else if (item['name'] == 'google_translation_key') {
            Config.googleTranslationKey = item['data'];
          }
        }
      }
    }
    EasyLoading.dismiss();
  }
}
